package cn.zhqr.core.component;

import cn.zhqr.common.bean.UserInfo;
import cn.zhqr.common.external.cache.CacheKit;
import cn.zhqr.common.external.cache.RedisCacheManager;
import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;

public class DefaultUserInfoManager implements UserInfoManager{
    private Logger logger = Logger.getLogger(DefaultUserInfoManager.class);
    private static final String USER_INFO_CACHE = "user_info_cache";
    private String keyPrefix = "user_auth_token";
    public int expiredSeconds = 24*3600*1000;

    public DefaultUserInfoManager(){
        CacheKit.addCacheManager(USER_INFO_CACHE,new RedisCacheManager(USER_INFO_CACHE));
    }

    @Override
    public void setUserInfo(String token, UserInfo userInfo){
        CacheKit.use(USER_INFO_CACHE).setEx(keyPrefix +token, expiredSeconds, JSON.toJSONString(userInfo));//每次访问更新token过期时间
        CacheKit.use(USER_INFO_CACHE).setEx(keyPrefix +"_user_"+userInfo.getUserid(), expiredSeconds,  token);
    }

    @Override
    public UserInfo getUserInfo(String token){
        Object value = CacheKit.use(USER_INFO_CACHE).get(keyPrefix +token);
        if (value != null) {
            try{
                return JSON.parseObject(String.valueOf(value), UserInfo.class);
            }catch (Exception e){
                logger.error("Parse userinfo string error ,value:"+value,e);
            }
        }
        return null;
    }

    @Override
    public void removeUserInfo(String token) {
        CacheKit.use(USER_INFO_CACHE).del(keyPrefix +token);
    }

    public String getKeyPrefix() {
        return keyPrefix;
    }

    public void setKeyPrefix(String keyPrefix) {
        this.keyPrefix = keyPrefix;
    }

    public int getExpiredSeconds() {
        return expiredSeconds;
    }

    public void setExpiredSeconds(int expiredSeconds) {
        this.expiredSeconds = expiredSeconds;
    }
}
